package pers.cjr.demo.component.ws.handler;

import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

@Component
public class DefaultHandler implements WebSocketHandler {

    /**
     *
     */
    private static CopyOnWriteArraySet<String> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 建立连接
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 缓存用户信息: userInfo
        webSocketSet.add(session.getAttributes().get("id").toString());
        System.err.println("建立了链接！" + session.getAttributes().get("id") + "，当前共：" + webSocketSet.size() + "个");
    }

    /**
     * 接收消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
    }

    /**
     * 发生错误
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // 清除用户缓存信息
        webSocketSet.remove(session.getAttributes().get("id").toString());
        System.err.println("发生错误，当前共：" + webSocketSet.size() + "个");
    }

    /**
     * 关闭连接
     *
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 清除用户缓存信息
        webSocketSet.remove(session.getAttributes().get("id").toString());
        System.err.println("关闭连接，当前共：" + webSocketSet.size() + "个");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}